import { Injectable } from '@nestjs/common'
import { CreateDepartmentDto } from './dto/create-department.dto'
import { UpdateDepartmentDto } from './dto/update-department.dto'
import { Repository, Not, IsNull } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { Department } from './entities/department.entity'
import { formatOptionData } from 'src/utils'
@Injectable()
export class DepartmentService {
  constructor(
    @InjectRepository(Department)
    private readonly department: Repository<Department>
  ) {}
  create(createDepartmentDto: CreateDepartmentDto) {
    const department = new Department()
    department.name = createDepartmentDto.name
    department.desc = createDepartmentDto.desc
    return this.department.save(department)
  }

  async findAll(params: {
    page: number
    pageSize: number
    isDelete?: boolean
  }) {
    const where = {}
    params.isDelete && (where['deleteDate'] = Not(IsNull()))
    const data = await this.department.find({
      where: { ...where },
      withDeleted: params.isDelete,
      skip: (params.page - 1) * params.pageSize,
      take: params.pageSize
    })
    const total = await this.department.count({
      where: { ...where },
      withDeleted: params.isDelete
    })
    return { data, total }
  }

  async findAllOption() {
    const data = await this.department.find()
    return formatOptionData(data)
  }

  update(id: number, updateDepartmentDto: UpdateDepartmentDto) {
    return this.department.update(id, updateDepartmentDto)
  }

  remove(ids: number[]) {
    return this.department.softDelete(ids)
  }

  thoroughRemove(ids: number[]) {
    return this.department.delete(ids)
  }

  restore(ids: number[]) {
    return this.department.restore(ids)
  }
}
